const { Service } = require('egg')
const iconv = require('iconv-lite') // 导入iconv-lite模块
const { tableToList } = require('../utils/tools')

function convertArrayFormat(arr) { // 用于构建相应格式json对象
  return arr.reduce((acc, subArr) => {
    const newObj = {
      N: subArr[0],
      T: subArr[2],
      C: subArr[1],
      G: subArr[3],
      S: subArr[4],
    }
    acc.push(newObj)
    return acc
  }, [])
}

module.exports = class CreditService extends Service {
  /**
   * * 学分修读情况
   * @return {Array} *
   */
  async table() {
    const Cookie = this.ctx.state.Cookie
    const apiUrl = `${this.ctx.state.baseUrl}/cssfjw/taglib/DataTable.jsp?tableId=5327008`
    const res1 = await this.ctx.curl(`${this.ctx.state.baseUrl}/cssfjw/jw/common/getStuGradeSpeciatyInfo.action`, {
      method: 'POST',
      headers: {
        Cookie,
        Referer: 'http://58.20.34.197:10115/cssfjw/student/pyfa.llkc.html?menucode=S20101',
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    const resultObj = JSON.parse((JSON.parse(iconv.decode(res1.data, 'gbk'))).result)
    const [nj, dwh, zydm] = [resultObj.nj, resultObj.dwh, resultObj.zydm]

    const res2 = await this.ctx.curl(apiUrl, {
      method: 'POST',
      data: {
        nj,
        yxdm: dwh,
        zydm,
      },
      headers: {
        Cookie,
        Referer: 'http://58.20.34.197:10115/cssfjw/student/wsxk.pyfadb.html?menucode=S40301',
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    const gbkString = iconv.decode(res2.data, 'gbk')
    // console.log('gbkString', gbkString);
    // const info = {};
    if (res2.status === 200) {
      try {
        const data = tableToList(gbkString, 'tbody')
        // 开始处理
        const details = []// 存放json格式的信息
        // 学分计算
        const data2 = JSON.parse(JSON.stringify(data))// 复制一份
        const All = data2[data2.length - 1][data2[data2.length - 1].length - 1]// 得到最后的全部学分信息
        console.log('All', All)
        const regex = /[\u4e00-\u9fa5]/g // 匹配所有汉字的正则表达式
        const result = All.replace(regex, '').replace(/：/g, '') // 替换所有匹配的汉字
        console.log('result', result)
        let credit = result.split('，')// 将逗号删除
        credit = credit.map((item) => item.trim())// 学分数组
        // console.log('credit', credit);

        // const type = [ '创新创业必修课', '公共必修课', '专业必修课', '专业任选课', '专业限选课', '创新创业任选课' ];
        const type = ['必修课', '任选课', '限选课']
        // const dataUp = [[], [], [], [], [], []];// 存放不同类别的学分
        const dataUp = [[], [], []]
        const table = []// 存放正确格式的数据
        // console.log('data', data);
        for (const i of data) {
          i.splice(1, 2)// 删掉多余数据
          i.splice(3, 2)
          i.splice(6, 2)
          i[1] = i[1].replace(/\[.*?\]/g, '')// 删掉课程前面的前缀
          // i[0] = i[0].replace(/课\//g, '');
          if (i[5].includes('通过')) {
            i[5] = '已获'
          } else {
            i[5] = '未获'
          }
          // if (i[0].includes('创新创业必修课')) { // 将不同类别分别存入相应数组
          //   dataUp[0].push(i);
          // } else if (i[0].includes('公共必修课')) {
          //   dataUp[1].push(i);
          // } else if (i[0].includes('专业必修课')) {
          //   dataUp[2].push(i);
          // } else if (i[0].includes('专业任选课')) {
          //   dataUp[3].push(i);
          // } else if (i[0].includes('专业限选课')) {
          //   dataUp[4].push(i);
          // } else if (i[0].includes('创新创业任选课')) {
          //   dataUp[5].push(i);
          // }
          if (i[0].includes('必修课')) {
            dataUp[0].push(i)
          } else if (i[0].includes('限选课')) {
            dataUp[1].push(i)
          } else if (i[0].includes('任选课')) {
            dataUp[2].push(i)
          }
        }
        for (const i of dataUp) { // 删掉多余信息
          for (const k of i) {
            k.splice(0, 1)
          }
          const data1 = convertArrayFormat(i)// 用于构建相应格式的json对象
          details.push(data1)
        }
        // console.log('details', details);
        let v = ''
        let k = ''
        for (let i = 0; i < details.length; i++) {
          // for (let i = 0; i < details.length; i++) {
          //   console.log('details[4]', details[4][0].S);
          // }
          if (credit[i]) {
            v = credit[i].split('/')[0]
            k = credit[i].split('/')[1]
          }
          // console.log('details.length', details.length);
          // console.log('details[4]', details[4][0].S);
          // if (details[i].S === '已获') {
          // console.log('details[i].G', details[i].G);
          // }
          const dataJson = {
            category: type[i],
            details: details[i],
            need: v,
            has: k,
          }
          table.push(dataJson)
        }
        return table
      } catch (err) {
        console.log(err)
      }
    }
    return []
  }

  /**
   * * 创新学分、素拓分、第二课堂分
   * @return {Array} *
   */
  async extra() {
    const Cookie = this.ctx.state.Cookie
    const apiUrl1 = `${this.ctx.state.baseUrl}/cssfjw/frame/normalusemenu/getBreadcrumbsInfoNew.action?menucode=S51602`
    const apiUrl2 = `${this.ctx.state.baseUrl}/cssfjw/reportprintpageservlet`
    const res1 = await this.ctx.curl(apiUrl1, {
      method: 'POST',
      headers: {
        Cookie,
        Referer: 'http://58.20.34.197:10115/cssfjw/student/pyfa.llkc.html?menucode=S20101',
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    const gbkString1 = iconv.decode(res1.data, 'gbk')
    const newObj = JSON.parse(gbkString1)
    const xmlTagName = newObj.linkfile.replace(/^.*\/xfrd\/cxcy\.([a-z]+).html$/, 'xfrd_$1')

    const res2 = await this.ctx.curl(apiUrl2, {
      method: 'POST',
      data: {
        xmlTagName,
      },
      headers: {
        Cookie,
        Referer: 'http://58.20.34.197:10115/cssfjw/student/stu.djks.zmsq.jsp?menucode=S40204',
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    const gbkString = iconv.decode(res2.data, 'gbk')

    const header = ['项目名称', '学分', '类型', '备注']
    // const header = [ '学期', '项目名称', '学分', '编号', '类型', '备注' ];

    if (res2.status === 200) {
      try {
        const data = tableToList(gbkString, 'tbody')

        // 开始处理
        for (const i of data) { // 删掉多余信息，交换顺序
          i.splice(0, 3)
          i.splice(2, 1)
          i.splice(3, 2)
          const v = i[1]
          const k = i[3]

          i[1] = i[0]
          i[0] = v

          i[3] = i[2]
          i[2] = k

          const j = i[1]
          i[1] = i[2]
          i[2] = j
        }
        // 结束处理

        const has = data[data.length - 1][1]
        data.splice(data.length - 1, 1)

        return { table: data, header, has }
      } catch (err) {
        return err
      }
    }
    return { table: [], header, has: '0' }
  }
}
